package com.egg.basic.service.quartz;

import com.egg.basic.entity.quartz.Quartz;
import com.egg.common.core.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

import static org.quartz.TriggerBuilder.newTrigger;

@Profile({"prod", "test", "dev"})
@Slf4j
@Component
public class QuartzManage {


    public static final String JOB_TASK = "TASK_";
    public static final String JOB_KEY = "JOB_KEY_";

    @Resource(name = "scheduler")
    private Scheduler scheduler;

    /**
     * 新增
     *
     * @param quartz
     */
    public void add(Quartz quartz) {
        // 构建job信息
        JobDetail jobDetail = JobBuilder.newJob(QuartzExecution.class).
                withIdentity(JOB_TASK + quartz.getId()).build();
        //通过触发器名和cron 表达式创建 Trigger
        Trigger cronTrigger = newTrigger()
                .withIdentity(JOB_TASK + quartz.getId())
                .startNow()
                .withSchedule(CronScheduleBuilder.cronSchedule(quartz.getCronExpression()))
                .build();
        cronTrigger.getJobDataMap().put(JOB_KEY, quartz);
        //重置启动时间
        ((CronTriggerImpl) cronTrigger).setStartTime(new Date());
        try {
            //执行定时任务
            scheduler.scheduleJob(jobDetail, cronTrigger);
        } catch (Exception e) {
            log.error("创建定时任务失败", e);
            throw new CustomException("创建定时任务失败");
        }
        // 暂停任务
        if (quartz.getPause()) {
            pause(quartz);
        }
    }

    /**
     * 删除
     *
     * @param quartz
     */
    public void delete(Quartz quartz) {
        try {
            JobKey jobKey = JobKey.jobKey(JOB_TASK + quartz.getId());
            scheduler.pauseJob(jobKey);
            scheduler.deleteJob(jobKey);
        } catch (Exception e) {
            log.error("删除定时任务失败", e);
            throw new CustomException("删除定时任务失败");
        }
    }

    /**
     * 恢复
     *
     * @param quartz
     */
    public void resume(Quartz quartz) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_TASK + quartz.getId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                add(quartz);
            }
            JobKey jobKey = JobKey.jobKey(JOB_TASK + quartz.getId());
            scheduler.resumeJob(jobKey);
        } catch (Exception e) {
            log.error("恢复定时任务失败", e);
            throw new CustomException("恢复定时任务失败");
        }
    }

    /**
     * 执行
     *
     * @param quartz
     */
    public void run(Quartz quartz) {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(JOB_TASK + quartz.getId());
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            // 如果不存在则创建一个定时任务
            if (trigger == null) {
                add(quartz);
            }
            JobDataMap dataMap = new JobDataMap();
            dataMap.put(JOB_KEY, quartz);
            JobKey jobKey = JobKey.jobKey(JOB_TASK + quartz.getId());
            scheduler.triggerJob(jobKey, dataMap);
        } catch (Exception e) {
            log.error("定时任务执行失败", e);
            throw new CustomException("定时任务执行失败");
        }
    }

    /**
     * 暂停
     *
     * @param quartz
     */
    public void pause(Quartz quartz) {
        try {
            JobKey jobKey = JobKey.jobKey(JOB_TASK + quartz.getId());
            scheduler.pauseJob(jobKey);
        } catch (Exception e) {
            log.error("定时任务暂停失败", e);
            throw new CustomException("定时任务暂停失败");
        }
    }


}
